<script setup lang="ts">
import * as echarts from 'echarts/core'
import {
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  DataZoomComponent,
  LegendComponent
} from 'echarts/components'
import { PieChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'
import { toRaw, ref, onMounted } from 'vue'
import {
  useDebounceFn,
  useIntersectionObserver,
  useResizeObserver
} from '@vueuse/core'

echarts.use([
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  DataZoomComponent,
  PieChart,
  CanvasRenderer,
  LegendComponent
])

const props = defineProps<{
  data: {
    legendData: string[]
    seriesData: {
      name: string
      value: number
    }[]
  }
}>()

const chartDom = ref<HTMLElement>()
let myChart: echarts.ECharts
function init() {
  if (!chartDom.value) return
  // const data = (await getPieApi()).result
  const data = toRaw(props.data)
  const option = {
    title: {
      text: '同名数量统计',
      subtext: '纯属虚构',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 20,
      bottom: 20,
      data: data.legendData
    },
    series: [
      {
        name: '姓名',
        type: 'pie',
        radius: '55%',
        center: ['40%', '50%'],
        data: data.seriesData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  myChart = echarts.init(chartDom.value)
  option && myChart.setOption(option)
}

/**懒加载 */
const { stop } = useIntersectionObserver(
  chartDom,
  async ([{ isIntersecting }]) => {
    if (isIntersecting) {
      init()
      stop()

      /**元素发生变化后的回调函数 */
      const debouncedFn = useDebounceFn(() => {
        myChart.resize()
      }, 1000)

      /**监听元素宽度发生变化 */
      useResizeObserver(chartDom, debouncedFn)
    }
  }
)
</script>

<template>
  <div ref="chartDom"></div>
</template>

<style lang="scss" scoped>
div {
  width: 100%;
  min-width: 700px;
  height: 500px;
}
</style>
